package link.chengguo.orangemall.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import link.chengguo.orangemall.annotation.IgnoreAuth;
import link.chengguo.orangemall.component.OssAliyunUtil;
import link.chengguo.orangemall.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Random;

/**
 * Oss相关操作接口
 * https://github.com/orangemall on 2018/4/26.
 */
@RestController
@Api(tags = "OssController", description = "Oss管理")
@RequestMapping("/api/aliyun/oss")
public class OssController {
    @Autowired
    OssAliyunUtil aliyunOSSUtil;

    private static ByteArrayInputStream getRandomDataStream(int length) {
        return new ByteArrayInputStream(getRandomBuffer(length));
    }

    private static byte[] getRandomBuffer(int length) {
        final Random randGenerator = new Random();
        final byte[] buff = new byte[length];
        randGenerator.nextBytes(buff);
        return buff;
    }

    @IgnoreAuth
    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public Object upload(@RequestParam("file") MultipartFile file) throws Exception {
        return new CommonResult().success(aliyunOSSUtil.upload(file));
    }

    @IgnoreAuth
    @PostMapping("/uploads")
    @ApiOperation("多文件上传文件")
    public Object uploads(@RequestPart("file") MultipartFile[] file) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        if (file != null && file.length > 0) {
            for (int i = 0; i < file.length; i++) {
                stringBuffer.append(aliyunOSSUtil.upload(file[i]) + ",");
            }
        }
        return new CommonResult().success(stringBuffer);
    }

    private String getFileExtension(String fileName) {
        int position = fileName.indexOf('.');
        if (position > 0) {
            String temp = fileName.substring(position);
            return temp;
        }
        return "";
    }
}
